package com.growthgate.bootcommon.util;

import org.apache.commons.io.IOUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 字符串工具类
 *
 * @author GrowthGate
 * @date 2019/11/11
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    @NotNull
    public static String randomUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Nullable
    public static Integer[] splitToInteger(@Nullable String str, @Nullable String separatorChars) {
        if (str == null) {
            return null;
        }
        String[] strArray = split(str, separatorChars);
        Integer[] array = new Integer[strArray.length];
        for (int i = 0; i < strArray.length; i++) {
            array[i] = Integer.parseInt(strArray[i]);
        }
        return array;
    }

    /**
     * html转义
     *
     * @param str 要转义的字符串
     * @return 转义后的字符串
     */
    @Nullable
    public static String toHtml(@Nullable String str) {
        return StringEscapeUtils.escapeHtml4(str);
    }

    /**
     * 压缩字符串（字符串过短，压缩反而会增加长度）
     *
     * @param str 要压缩的字符串
     * @return 压缩后的字符串
     */
    @Nullable
    public static String zip(@Nullable String str) {
        if (isEmpty(str)) {
            return str;
        }
        // 转为url字符串（为了剔除中文字符）
        str = UrlUtils.encode(str);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipos = new GZIPOutputStream(baos)) {
            gzipos.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeBase64String(baos.toByteArray());
    }

    /**
     * 解压缩字符串
     *
     * @param str 压缩后的字符串
     * @return 原字符串
     */
    @Nullable
    public static String unzip(@Nullable String str) {
        if (isEmpty(str)) {
            return str;
        }
        byte[] bytes = Base64.decodeBase64(str);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); GZIPInputStream gzipis = new GZIPInputStream(bais)) {
            IOUtils.copy(gzipis, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        str = baos.toString();
        // 转回中文字符串
        return UrlUtils.decode(str);
    }

}